package com.demo.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import eu.medsea.mimeutil.MimeUtil;
@SuppressWarnings("all")
public class FileExportUtils {
	private static Log logger = LogFactory.getLog(FileExportUtils.class);
	private static boolean isinit=false;
	private static Set<String> imageSuffix = new HashSet();

	static {
		imageSuffix.add("BMP");
		imageSuffix.add("DUB");
		imageSuffix.add("GIF");
		imageSuffix.add("JFIF");
		imageSuffix.add("JPE");
		imageSuffix.add("JPEG");
		imageSuffix.add("JPG");
		imageSuffix.add("PNG");
		imageSuffix.add("TIF");
		imageSuffix.add("TIFF");
		imageSuffix.add("ICO");
	}

	public static void exportTxt(List<Map<String, Object>> lists, OutputStream os, String charsplit) {
		BufferedOutputStream bos = new BufferedOutputStream(os);

		if ((charsplit == null) || ("t".equals(charsplit))) {
			charsplit = "\t";
		}
		StringBuffer sbcols = new StringBuffer();
		for (Map mp : lists) {
			Set key = mp.keySet();
			for (Iterator it = key.iterator(); it.hasNext();) {
				sbcols.append(mp.get(it.next()));
				sbcols.append(charsplit);
			}
			sbcols.append("\r\n");
		}
		try {
			bos.write(sbcols.toString().getBytes("GBK"));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);

			if (bos != null)
				try {
					bos.close();
				} catch (IOException ex) {
					logger.error(ex.getMessage(), ex);
				}
		} finally {
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
		}
	}

	public static void exportCsv(List<Map<String, Object>> lists, OutputStream os) {
		exportTxt(lists, os, null);
	}

	public static String getFileNameByPath(String path) {
		if (path.lastIndexOf("/") > -1) {
			path = path.substring(path.lastIndexOf("/") + 1);
		}

		if (path.lastIndexOf("\\") > -1) {
			path = path.substring(path.lastIndexOf("\\") + 1);
		}

		return path;
	}

	public static String filterPath(String path) {
		if ((!StringUtils.isBlank(path)) && (!path.endsWith(File.separator))) {
			if ((path.endsWith("\\")) || (path.endsWith("/"))) {
				path = path.substring(0, path.length() - 1);
			}
			path = path + File.separator;
		}

		return path;
	}

	public static String getSuffix(String fileName) {
		return String.valueOf(fileName.substring(fileName.lastIndexOf(".") + 1)).toUpperCase();
	}

	public static byte[] is2byte(InputStream in) throws IOException {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[10240];
		int count = -1;
		while ((count = in.read(data, 0, 10240)) != -1) {
			outStream.write(data, 0, count);
		}
		data = (byte[]) null;
		return outStream.toByteArray();
	}

	public static boolean isImage(String fileName) {
		boolean isImage = false;

		if (!StringUtils.isBlank(fileName)) {
			String fileSuffix = getSuffix(fileName);

			isImage = imageSuffix.contains(fileSuffix);
		}

		return isImage;
	}
	
	public static String getMine(String file) {
		if(!isinit){
			MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.ExtensionMimeDetector");
			isinit=true;
		}
		return MimeUtil.getMimeTypes(file).iterator().next().toString();
	}
	
	public static void download(HttpServletResponse response, String filename,
			String mimetype, File file,String type) throws Exception {
		OutputStream os = null;
		try {
			response.reset();
			response.setContentType(mimetype + "; charset=utf-8");
			
			if ("inline".equals(type)) {
				response.setHeader("Content-Disposition","; filename=" + URLEncoder.encode(filename, "UTF-8"));
			}else{
				response.setHeader("Content-disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
			}
			if (!file.exists()) {
				throw new Exception("文件没找到");
			}
			os = response.getOutputStream();
			byte[] array = FileExportUtils.file2byte(file);
			response.setContentLength(array.length);
			os.write(array);
			os.flush();
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}
	
	public static byte[] file2byte(String filePath){  
        byte[] buffer = null;  
        try  
        {  
            File file = new File(filePath);  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            byte[] b = new byte[1024];  
            int n;  
            while ((n = fis.read(b)) != -1)  
            {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        }  
        catch (FileNotFoundException e)  
        {  
            e.printStackTrace();  
        }  
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
        return buffer;  
    }
	
	public static byte[] file2byte(File file){  
		if(!file.exists()) return null;
        byte[] buffer = null;  
        try  
        {  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            byte[] b = new byte[1024];  
            int n;  
            while ((n = fis.read(b)) != -1)  
            {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        }  
        catch (FileNotFoundException e)  
        {  
            e.printStackTrace();  
        }  
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
        return buffer;  
    }
  
    public static void byte2File(byte[] buf, String filePath, String fileName){  
        BufferedOutputStream bos = null;  
        FileOutputStream fos = null;  
        File file = null;  
        try  
        {  
            File dir = new File(filePath);  
            if (!dir.exists() && dir.isDirectory())  
            {  
                dir.mkdirs();  
            }  
            file = new File(filePath + File.separator + fileName);  
            fos = new FileOutputStream(file);  
            bos = new BufferedOutputStream(fos);  
            bos.write(buf);  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
        finally  
        {  
            if (bos != null)  
            {  
                try  
                {  
                    bos.close();  
                }  
                catch (IOException e)  
                {  
                    e.printStackTrace();  
                }  
            }  
            if (fos != null)  
            {  
                try  
                {  
                    fos.close();  
                }  
                catch (IOException e)  
                {  
                    e.printStackTrace();  
                }  
            }  
        }  
    } 
}